<template>
  <div class="result-container">
    <!-- 基本信息+图表组合卡片 -->
    <el-card class="info-card">
      <template #header>
        <div class="card-header">
          <span class="title">测评概览</span>
        </div>
      </template>
      <el-row :gutter="20">
        <el-col :span="4">
          <div class="desc-container">
            <el-descriptions :column="1" border style="line-height:100px">
              <el-descriptions-item label="测评标题">{{ paperTitle }}</el-descriptions-item>
              <el-descriptions-item label="提交时间">{{ formattedDate }}</el-descriptions-item>
              <el-descriptions-item label="答题耗时">
                <el-tag type="primary">{{totalTime}}</el-tag>
              </el-descriptions-item>
              <el-descriptions-item label="测评状态">
                <el-tag type="success">{{ status === '1' ? '已完成' : '未完成' }}</el-tag>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-col>
        <el-col :span="20">
          <el-row :gutter="20">
            <el-col :span="12">
              <div class="chart-card">
                <h4 class="chart-title">维度分布</h4>
                <div class="chart-container">
                  <template v-if="factorData.length">
                    <v-chart :option="pieOption" autoresize/>
                  </template>
                  <el-empty v-else description="数据加载中..." :image-size="80"/>
                </div>
              </div>
            </el-col>
            <el-col :span="12">
              <div class="chart-card">
                <h4 class="chart-title">能力雷达</h4>
                <div class="chart-container">
                  <template v-if="factorData.length">
                    <v-chart :option="radarOption"/>
                  </template>
                  <el-empty v-else description="数据加载中..." :image-size="80"/>
                </div>
              </div>
            </el-col>
          </el-row>
        </el-col>
      </el-row>
    </el-card>

    <!-- 因子得分卡片 -->
    <el-card class="factor-card">
      <template #header>
        <div class="card-header">
          <span class="title">维度得分分析</span>
        </div>
      </template>
      <el-table :data="factorData" stripe style="width: 100%">
        <el-table-column prop="name" label="心理维度" width="180"/>
        <el-table-column prop="score" label="得分" width="120">
          <template #default="{row}">
            <el-rate v-model="row.score"
                     disabled :max="10"
                     :colors="scoreColors"
                     show-score
            />
          </template>
        </el-table-column>
        <el-table-column prop="desc" label="简要说明"/>
      </el-table>
    </el-card>

    <!-- 详细分析卡片 -->
    <!--<el-card class="analysis-card">
      <template #header>
        <div class="card-header">
          <span class="title">专业分析报告</span>
        </div>
      </template>
      <div class="analysis-section">
        <h3 class="section-title">情绪稳定性分析</h3>
        <p class="section-content">您的情绪稳定性处于中等水平，建议通过正念练习提升情绪调节能力。</p>
      </div>
      <div class="analysis-section">
        <h3 class="section-title">人际关系评估</h3>
        <p class="section-content">表现出良好的社交适应性，但存在轻度社交回避倾向。</p>
      </div>
      <div class="analysis-section">
        <h3 class="section-title">压力应对建议</h3>
        <p class="section-content">推荐尝试认知行为疗法（CBT）缓解日常压力。</p>
      </div>
    </el-card>-->

    <!-- 操作按钮组 -->
    <div class="action-btns">
      <el-button type="info" @click="handleBack">返回列表</el-button>
      <el-button type="success" @click="handleRetestAssessment(paperId)">重新测评</el-button>
      <el-button type="primary" @click="handleAIAnalysis">
        <el-icon>
          <MagicStick/>
        </el-icon>
        AI深度解读
      </el-button>
    </div>
  </div>
</template>

<script setup>
import {ref} from 'vue'
import {MagicStick} from '@element-plus/icons-vue'
import {use} from 'echarts/core'
import {CanvasRenderer} from 'echarts/renderers'
import {BarChart, PieChart, RadarChart} from 'echarts/charts'
import {LegendComponent, TitleComponent, TooltipComponent,} from 'echarts/components'
import VChart from 'vue-echarts'
import {retestAssessment} from "@/api/record/record.js";
import {generalScore} from "@/api/answer/answer.js";
// 初始化ECharts
use([
  CanvasRenderer,
  PieChart,
  RadarChart,
  BarChart,
  TitleComponent,
  TooltipComponent,
  LegendComponent,
])
// 雷达图配置
const radarOption = computed(() => ({
  title: {
    text: '心理维度雷达图',
    left: 'center',
    top: '5px', // 上移标题
    textStyle: {
      color: '#606266',
      fontSize: 16,
      padding: [5, 0] // 增加垂直内边距
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: (params) => {
      return `${params.name}<br/>得分：${params.value}`
    }
  },
  radar: {
    center: ['50%', '55%'], // 调整中心位置
    radius: '70%', // 缩小半径
    shape: 'polygon',
    splitNumber: 5,
    axisLine: {
      lineStyle: {
        color: 'rgba(100, 100, 100, 0.3)'
      }
    },
    splitLine: {
      lineStyle: {
        color: 'rgba(100, 100, 100, 0.1)'
      }
    },
    indicator: factorData.value.length ?
        factorData.value.map(item => ({
          name: item.name,
          max: 10,
          color: '#666'
        })) :
        [{name: '加载中...', max: 10}]
  },
  series: [{
    type: 'radar',
    data: [{
      value: factorData.value.map(item => item.score),
      name: '维度得分',
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 2,
        type: 'dashed'
      },
      areaStyle: {
        color: {
          type: 'linear',
          x: 0,
          y: 0,
          x2: 0,
          y2: 1,
          colorStops: [{
            offset: 0, color: 'rgba(92, 155, 242, 0.8)'
          }, {
            offset: 1, color: 'rgba(92, 155, 242, 0.2)'
          }]
        }
      },
      itemStyle: {
        color: '#5c9bf2'
      }
    }]
  }],
  textStyle: {
    fontFamily: 'Arial, sans-serif'
  }
}))
// 优化饼图配置
const pieOption = computed(() => ({
  title: {
    text: '维度分布',
    left: 'center',
    top: '10px', // 上移标题
    textStyle: {
      fontSize: 14,
      color: '#606266'
    }
  },
  tooltip: {
    trigger: 'item',
    formatter: ({name, percent, value}) =>
        `${name}<br>得分：${value}<br>占比：${percent}%`
  },
  legend: {
    orient: 'vertical',
    right: '5%',        // 调整为相对容器的右侧距离
    top: 'middle',      // 垂直居中
    align: 'left',      // 左对齐文本
    itemGap: 12,        // 图例项间距
    itemWidth: 10,      // 图例标记宽度
    itemHeight: 12,     // 图例标记高度
    padding: [0, 20],   // 右侧增加间距
    formatter: name => {
      const item = factorData.value.find(v => v.name === name)
      return item ? `${name} (${item.score}分)` : name
    }
  },
  series: [{
    type: 'pie',
    center: ['35%', '55%'], // 调整饼图位置
    radius: ['35%', '65%'],
    data: factorData.value.length
        ? factorData.value.map(item => ({
          name: item.name,
          value: item.score
        }))
        : [{name: '暂无数据', value: 0}], // 空数据兜底
    label: {
      show: true,
      formatter: '{b}: {d}%'
    }
  }]
}))

const {proxy} = getCurrentInstance();

const paperId = ref(proxy.$route.query.paperId);
const delFlag = ref(proxy.$route.query.delFlag);
const paperTitle = ref(null);
const submitTime = ref(null);
const totalTime = ref(null);
const status = ref(null)
const formattedDate = ref(null);

// 因子得分数据
const factorData = ref([]);
// 分数颜色映射
const scoreColors = ref(['#99A9BF', '#F7BA2A', '#FF9900'])

// 按钮事件处理
const handleBack = () => {
  // 返回逻辑
  console.log('返回测评列表')
  proxy.$router.push({path: '/history'})
}

// 重新测评
const handleRetestAssessment = (paperId) => {
  console.log('重新测评', paperId)
  retestAssessment(paperId).then(response => {
    if (response) {
      proxy.$router.push({
        path: '/online-assessments/examPage',
        query: {  // 使用 query 传参
          paperId: paperId,
        }
      })
    }
  })
}
// AI分析逻辑
const handleAIAnalysis = () => {
  console.log('发起AI分析请求')
  // todo 跳转到AI分析页逻辑。暂定为 /askAi 页面
  proxy.$router.push({
    path: '/askAi',
    query: {  // 使用 query 传参
      paperId: paperId.value,
    }
  })
}

// 转换提交时间
function formatterDate() {
  formattedDate.value = new Intl.DateTimeFormat('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false
  }).format(new Date(submitTime.value)).replace(/\//g, '-');
}

// 获取测评结果详情
function getScore() {
  generalScore(paperId.value, delFlag.value).then(response => {
    console.log("提交后获取总结果：", response)
    paperTitle.value = response.data.paperTitle;
    submitTime.value = response.data.submitTime;
    totalTime.value = response.data.totalTime;
    status.value = response.data.status;
    factorData.value = response.data.symptomClusterDTOList
    formatterDate();
  })
}

onMounted(() => {
  getScore();
})
</script>

<style scoped>
.desc-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center; /* 垂直居中 */
}

/* 调整描述项间距 */
:deep(.el-descriptions) {
  margin: 0 !important;
}

:deep(.el-descriptions-item__container) {
  align-items: center; /* 内容垂直居中 */
}

:deep(.el-descriptions-item__label) {
  background: #f8f9fa !important; /* 保持背景色一致 */
}

.info-card {
  min-height: 200px;
}

.section-title {
  color: #87CEEB;
}

/* 增加整体间距 */
.result-container {
  background: linear-gradient(135deg, #f0f9ff 0%, #ffffff 100%);
  min-height: 90vh;
  padding: 25px 30px; /* 增加内边距 */
  box-sizing: border-box;
}

/* 统一卡片间距 */
.el-card {
  margin-bottom: 10px; /* 增大卡片间距 */
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease; /* 添加过渡效果 */
}

/* 图表卡片样式调整 */
.chart-card {
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.chart-title {
  margin: 0 0 15px 10px;
  color: #2c3e50;
  font-size: 15px;
  font-weight: 600;
}

/* 图表容器优化 */
.chart-container {
  padding: 15px 20px !important;
  height: 320px !important; /* 确保固定高度 */
  position: relative;

  .echarts {
    width: 100% !important;
    height: 100% !important;
    min-height: 300px;
  }
}

/* 雷达图特殊调整 */
.echarts-radar {
  padding-top: 20px; /* 增加顶部间距 */
}

@media (max-width: 768px) {
  .result-container {
    padding: 15px;
  }

  .chart-container {
    height: 280px !important;
    padding: 10px;
  }

  .chart-title {
    font-size: 14px;
    margin-left: 5px;
  }
}

/* 增加分析报告间距 */
.analysis-section {
  margin-bottom: 28px; /* 增大分析块间距 */
  padding: 20px; /* 增加内边距 */
  background: #f8fafc;
  border-radius: 8px;
  transition: all 0.3s ease;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  }
}

/* 按钮组间距优化 */
.action-btns {
  margin-top: 30px; /* 增加顶部间距 */
  padding: 25px 0;
}
</style>
